﻿using IdentifyTest.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal;
using Microsoft.AspNetCore.Mvc;

namespace IdentifyTest.Controllers
{
    public class AccountController : Controller
    {
        //注入登录管理服务   IdentityUser是当前登录用户Model
        private readonly SignInManager<IdentityUser> _signInManager;

        private readonly UserManager<IdentityUser> _userManager;//注入用户管理服务

        //构造函数注入
        public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
        {
            _signInManager = signInManager;
            _userManager = userManager;
        }

        public IActionResult Login()
        {
            return View();
        }


        /// <summary>
        /// 登录提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SubmitLogion(LoginViewMode model)
        {
            if (ModelState.IsValid)
            {
                //获取用户类 IdentityUser
                var user = await _signInManager.UserManager.FindByNameAsync(model.UserName);
                if (user != null)
                {
                    //await _signInManager.SignInAsync(user, false, model.Password);
                    //false ：表示下次进入系统需要重新输入用户名和密码
                    //true:  保存用户名和密码密码
                    //IsPresistented 是否登录持久化
                    var result = await _signInManager.PasswordSignInAsync(user, model.Password, false, false);//LockoutonFailure :登录失败时是否锁定密码
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Login");
                    }
                }
                ModelState.AddModelError("", "用户名或者密码输入不正确");
            }

            return View("Login", model);
        }


        public IActionResult Register()
        {
            return View();
        }


        /// <summary>
        /// 注册提交
        /// </summary>
        /// <param name="registerModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SubmitReqister(RegisterViewModel registerModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.CreateAsync(new IdentityUser
                {
                    UserName = registerModel.UserName,
                    Email = registerModel.Email
                }, registerModel.Password);
                if (user.Succeeded)
                {
                    return RedirectToAction("Index", "Home");//登录成功跳转到首页
                }

                foreach (var errot in user.Errors)
                {
                    ModelState.AddModelError("", errot.Description);
                }

            }
            return RedirectToAction("Register",registerModel);
        }
    }
}
